package com.magicborrow.activity;

import android.app.Dialog;
import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TabHost;
import android.widget.TextView;

import com.easemob.chat.CmdMessageBody;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMMessage;
import com.magicborrow.Constants;
import com.magicborrow.MagicBorrowApplication;
import com.magicborrow.R;
import com.magicborrow.huanxin.ChatHistoryActivity;
import com.magicborrow.utils.SharePreUtils;
import com.magicborrow.utils.UserTools;
import com.magicborrow.views.MagicDialog;


public class MainActivity extends TabActivity implements RadioGroup.OnCheckedChangeListener, View.OnClickListener {

    private TabHost tabHost;
    private RadioGroup radioGroup;
    private Intent homeIntent;
    private Intent findIntent;
    private Intent msgIntent;
    private Intent mineIntent;
    private View pop;
    private Button btnMain;
    private TextView jiaobiaoNumber;
    private TextView jiaobiaoNumber4;
    public static MainActivity instans;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        instans = this;
        // 注册一个cmd消息的BroadcastReceiver  这段代码不要删 环信需要
        IntentFilter cmdIntentFilter = new IntentFilter(EMChatManager.getInstance().getCmdMessageBroadcastAction());
        registerReceiver(cmdMessageReceiver, cmdIntentFilter);
        EMChat.getInstance().setAppInited();

        MagicBorrowApplication.getInstance().setMainActivty(this);
       // UmengUpdateUtil.prepare4UmengUpdate(this);
        tabHost = getTabHost();
        radioGroup = (RadioGroup) findViewById(R.id.rg_main);
        pop = findViewById(R.id.rl_pop);
        btnMain = (Button) findViewById(R.id.btn_main);
        findViewById(R.id.tv_push).setOnClickListener(this);
        findViewById(R.id.tv_borrow).setOnClickListener(this);
        jiaobiaoNumber = (TextView)findViewById(R.id.jiaobiaoNumber5);
        jiaobiaoNumber4 = (TextView)findViewById(R.id.jiaobiaoNumber4);
        pop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (pop.getVisibility() == View.VISIBLE) {
                    popDismiss();
                }
            }
        });
        initIntent();
        radioGroup.setOnCheckedChangeListener(this);
        initTabs();
        //  initPop();
        btnMain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (pop.getVisibility() == View.VISIBLE) {
                    popDismiss();
                } else {
                    Animation animation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.bottom_navigation_show);
                    Animation animation1 = AnimationUtils.loadAnimation(MainActivity.this, R.anim.pop_show);
                    pop.startAnimation(animation1);
                    pop.setVisibility(View.VISIBLE);
                    btnMain.startAnimation(animation);
                }
            }
        });

    }

//    private void checkUpdate() {
//        VolleyTool.get("", null, new VolleyTool.HTTPListener() {
//            @Override
//            public <T> void onResponse(T t, int requestCode) {
//                //获得接口数据，和当前的版本号进行比对
//                //如果版本号一致，则不进行更新操作，否则进行更新操作
//                Message message = handler.obtainMessage();
//                if (true){
//                    message.what=SAME;
//                }else{
//                    message.what=UPDATE;
//                    message.obj="版本更新的描述";
//                }
//                handler.sendMessage(message);
//            }
//
//            @Override
//            public void onErrorResponse(VolleyError error, int requestCode) {
//
//            }
//        },0,null);
//    }


//    private Handler handler=new Handler(){
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//            switch (msg.what){
//                case SAME:
//                    break;
//                case UPDATE://弹出对话框提示是否下载更新
//                    showUpdateDialog((String)msg.obj);
//                    break;
//            }
//        }
//    };
    /**
     * cmd消息BroadcastReceiver
     */
    private BroadcastReceiver cmdMessageReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            //获取cmd message对象
            String msgId = intent.getStringExtra("msgid");
            EMMessage message = intent.getParcelableExtra("message");
            //获取消息body
            CmdMessageBody cmdMsgBody = (CmdMessageBody) message.getBody();
            String aciton = cmdMsgBody.action;//获取自定义action
            //获取扩展属性
//            String attr = "";
//            try {
//                attr = message.getStringAttribute("ext");
//            } catch (EaseMobEßxception e) {
//                e.printStackTrace();
//            }
//            Log.e("xxxxxxxxxxx",attr);
        }
    };


    public void setTabHost(int tab){
        ((RadioButton) radioGroup.getChildAt(tab > 1 ? tab + 1 : tab)).setChecked(true);
    }






    @Override
    protected void onResume() {
        super.onResume();
        Animation animation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.bottom_navigation_dismiss);
        //  btnMain.setAnimation(animation);
        btnMain.startAnimation(animation);
        int tab = tabHost.getCurrentTab();
        ((RadioButton) radioGroup.getChildAt(tab > 1 ? tab + 1 : tab)).setChecked(true);

        // BaseLog.e("xxxxxx", MD5.getMD5(MD5.getMD5(user.getPassword()));

        jiaobiao();
    }

    private void jiaobiao(){
        int one = SharePreUtils.getInt(this, Constants.APPLY,0);
        int two = SharePreUtils.getInt(this, Constants.BORROW,0);
        int three = SharePreUtils.getInt(this, Constants.CLAIM,0);
        int four = SharePreUtils.getInt(this, Constants.DONE,0);
        int totalCount = one+two+three+four;
        if(totalCount > 0){
            jiaobiaoNumber.setVisibility(View.VISIBLE);
            if(totalCount > 99){
                jiaobiaoNumber.setText(totalCount+"+");
            }else{
                jiaobiaoNumber.setText(totalCount+"");
            }

        }else{
            jiaobiaoNumber.setVisibility(View.GONE);
        }
        int message = SharePreUtils.getInt(this,Constants.MESSAGES,0);
        if(message > 0){
            jiaobiaoNumber4.setVisibility(View.VISIBLE);
            if(message > 99){
                jiaobiaoNumber4.setText(message+"+");
            }else{
                jiaobiaoNumber4.setText(message+"");
            }

        }else{
            jiaobiaoNumber4.setVisibility(View.GONE);
        }
    }

    public void toFindActivity() {
        ((RadioButton) radioGroup.getChildAt(1)).setChecked(true);
    }


    @Override
    protected void onPause() {
        super.onPause();

        if (pop != null && pop.getVisibility() == View.VISIBLE) {
            pop.setVisibility(View.GONE);

        }
    }

    @Override
    public void onBackPressed() {
        Log.i("===", "back0");
        if (pop.getVisibility() == View.VISIBLE) {
            popDismiss();
            Log.i("===", "back1");
            return;
        }
        super.onBackPressed();
    }


    private void popDismiss() {
        Animation animation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.bottom_navigation_dismiss);
        btnMain.startAnimation(animation);
        Animation animation1 = AnimationUtils.loadAnimation(MainActivity.this, R.anim.pop_dismiss);

        pop.startAnimation(animation1);

        pop.setVisibility(View.GONE);
    }


    private void initTabs() {
        tabHost.addTab(buildTbs("home", homeIntent));
        tabHost.addTab(buildTbs("find", findIntent));
        tabHost.addTab(buildTbs("msg", msgIntent));
        tabHost.addTab(buildTbs("mine", mineIntent));
    }

    private TabHost.TabSpec buildTbs(String tag, Intent intent) {
        return tabHost.newTabSpec(tag)
                .setIndicator(tag)
                .setContent(intent);
    }

    private void initIntent() {
        homeIntent = new Intent(this, HomeActivity.class);
        findIntent = new Intent(this, FindActivity.class);
        msgIntent = new Intent(this, ChatHistoryActivity.class);
        mineIntent = new Intent(this, MineActivity.class);
    }


    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {
        jiaobiao();
        switch (i) {
            case R.id.rb_0:
                tabHost.setCurrentTab(0);
                break;
            case R.id.rb_1:
                tabHost.setCurrentTab(1);
                break;
            case R.id.rb_2:
                if (!UserTools.isLogin(this, true)) {
                    int tab = tabHost.getCurrentTab();
                    ((RadioButton) radioGroup.getChildAt(tab > 1 ? tab + 1 : tab)).setChecked(true);
                    return;
                }
                tabHost.setCurrentTab(2);
                SharePreUtils.putInt(this,Constants.MESSAGES,0);
                break;
            case R.id.rb_3:
                if (!UserTools.isLogin(this, true)) {
                    int tab = tabHost.getCurrentTab();
                    ((RadioButton) radioGroup.getChildAt(tab > 1 ? tab + 1 : tab)).setChecked(true);
                    return;
                }
                tabHost.setCurrentTab(3);
                break;
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.tv_borrow:
                if (!UserTools.isLogin(this, true))
                    return;
                intent = new Intent(this, WantBorrowingActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_push:
                if (!UserTools.isLogin(this, true))
                    return;
                intent = new Intent(this, PushStuffActivity.class);
                startActivity(intent);
                break;
        }
    }
}
